# encoding: utf-8
from datetime import datetime
from random import sample

from flask import flash, redirect, render_template, url_for
from markdown import markdown

from exts import mongo

from . import bp_post
from .forms import Add_atricle


@bp_post.route('/')
def blog_index():
    '''读取所有文件标题'''
    all_article = mongo.db.blog_article.find({}, {'blog_title': 1, '_id': 0})
    # 所有文章发表时间
    all_created_times = mongo.db.blog_article.find(
        {}, {'created_time': 1, '_id': 0})
    return render_template('index.html', all_article=all_article, all_created_times=all_created_times)


@bp_post.route('/blog/<blog_title>/')
def blog_info(blog_title):
    '''使用文章标题做为参数,查询该文章信息.返回与标题数量相同的label,用于渲染HTML'''
    atricle_instance = mongo.db.blog_article.find_one_or_404(
        {'blog_title': blog_title})
    all_labels = ['label-default', 'label-primary', 'label-success',
                  'label-info', 'label-warning', 'label-danger']
    labels = sample(all_labels, len(atricle_instance['tags']))
    return render_template('blog_content.html', article=atricle_instance, labels_tags=zip(labels, atricle_instance['tags']))


@bp_post.route('/blog/add/', methods=['POST', 'GET'])
def blog_add():
    '''发表文章'''
    form = Add_atricle()
    if form.validate_on_submit():
        title = form.title.data
        tags = form.tags.data
        content = form.content.data
        created_time = datetime.utcnow()
        author = 'admin'
        new_article = mongo.db.blog_article.insert_one(
            {'blog_title': title, 'created_time': created_time, 'author': author, 'tags': tags.split(','), 'blog_content': markdown(content, output_format='html')})
        flash(u'添加成功')
        return redirect(url_for('bp_post.blog_info', blog_title=title))
    return render_template('add_article.html', form=form)
